"""
区域分析API路由
提供区域分析相关的API接口
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from typing import Optional, Dict, Any, List
from pydantic import BaseModel, Field
from datetime import datetime
from sqlalchemy.orm import Session

from core.database import get_db
from core.auth import get_current_active_user
from models.user import User
from services.analysis.regional_analyzer import RegionalAnalyzer, RegionalAnalysisFilters
from services.analysis.base_analyzer import get_analysis_service

# 创建路由器
regional_analysis_router = APIRouter()

# 请求模型
class RegionalAnalysisRequest(BaseModel):
    """区域分析请求模型"""
    task_id: Optional[int] = Field(None, description="分析任务ID")
    start_date: Optional[datetime] = Field(None, description="开始时间")
    end_date: Optional[datetime] = Field(None, description="结束时间")
    region: Optional[str] = Field(None, description="区域筛选")
    region_level: Optional[str] = Field(None, description="区域级别: city, district, street")
    has_coordinates: Optional[bool] = Field(None, description="是否有经纬度")
    min_confidence: Optional[float] = Field(None, ge=0.0, le=1.0, description="最小置信度")
    limit: Optional[int] = Field(1000, ge=1, le=10000, description="返回记录限制")
    offset: Optional[int] = Field(0, ge=0, description="偏移量")

class RegionalStatisticsRequest(BaseModel):
    """区域统计请求模型"""
    region: str = Field(..., description="区域名称")
    task_id: Optional[int] = Field(None, description="分析任务ID")
    start_date: Optional[datetime] = Field(None, description="开始时间")
    end_date: Optional[datetime] = Field(None, description="结束时间")

class HeatmapRequest(BaseModel):
    """热力图请求模型"""
    task_id: Optional[int] = Field(None, description="分析任务ID")
    start_date: Optional[datetime] = Field(None, description="开始时间")
    end_date: Optional[datetime] = Field(None, description="结束时间")
    region: Optional[str] = Field(None, description="区域筛选")
    min_confidence: Optional[float] = Field(None, ge=0.0, le=1.0, description="最小置信度")
    limit: Optional[int] = Field(5000, ge=1, le=20000, description="返回点数限制")


@regional_analysis_router.post("/analyze")
async def analyze_regional_data(
    request: RegionalAnalysisRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    执行区域分析

    返回完整的区域分析结果，包括：
    - 基础统计信息
    - 区域分布数据
    - 地理坐标数据
    - 置信度分布
    - 时间序列数据
    """
    try:
        # 创建过滤器
        filters = RegionalAnalysisFilters()
        filters.task_id = request.task_id
        filters.start_date = request.start_date
        filters.end_date = request.end_date
        filters.region = request.region
        filters.region_level = request.region_level
        filters.has_coordinates = request.has_coordinates
        filters.min_confidence = request.min_confidence
        filters.limit = request.limit
        filters.offset = request.offset

        # 执行分析
        analyzer = RegionalAnalyzer(db)
        result = analyzer.analyze_data(filters)

        if not result.success:
            raise HTTPException(status_code=400, detail=result.message)

        return {
            "code": 200,
            "message": "区域分析完成",
            "data": result.data,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"区域分析失败: {str(e)}")


@regional_analysis_router.get("/distribution")
async def get_regional_distribution(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    region_level: Optional[str] = Query(None, description="区域级别: city, district, street"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    region: Optional[str] = Query(None, description="区域筛选"),
    limit: Optional[int] = Query(20, ge=1, le=100, description="返回区域数量限制"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取区域分布统计数据"""
    try:
        filters = RegionalAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.region = region
        filters.region_level = region_level
        filters.limit = limit

        analyzer = RegionalAnalyzer(db)
        query = analyzer.build_base_query(filters)
        distribution = analyzer.get_regional_distribution(query, filters)

        return {
            "code": 200,
            "message": "获取区域分布成功",
            "data": distribution,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取区域分布失败: {str(e)}")


@regional_analysis_router.get("/geographical-data")
async def get_geographical_data(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    region: Optional[str] = Query(None, description="区域筛选"),
    has_coordinates: Optional[bool] = Query(True, description="是否只返回有坐标的数据"),
    min_confidence: Optional[float] = Query(None, ge=0.0, le=1.0, description="最小置信度"),
    limit: Optional[int] = Query(1000, ge=1, le=5000, description="返回点数限制"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取地理坐标数据（用于地图可视化）"""
    try:
        filters = RegionalAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.region = region
        filters.has_coordinates = has_coordinates
        filters.min_confidence = min_confidence
        filters.limit = limit

        analyzer = RegionalAnalyzer(db)
        query = analyzer.build_base_query(filters)
        geo_data = analyzer.get_geographical_data(query, filters)

        return {
            "code": 200,
            "message": "获取地理数据成功",
            "data": geo_data,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取地理数据失败: {str(e)}")


@regional_analysis_router.get("/heatmap")
async def get_heatmap_data(
    request: HeatmapRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取热力图数据"""
    try:
        filters = RegionalAnalysisFilters()
        filters.task_id = request.task_id
        filters.start_date = request.start_date
        filters.end_date = request.end_date
        filters.region = request.region
        filters.min_confidence = request.min_confidence
        filters.limit = request.limit

        analyzer = RegionalAnalyzer(db)
        heatmap_data = analyzer.get_heatmap_data(filters)

        return {
            "code": 200,
            "message": "获取热力图数据成功",
            "data": heatmap_data,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取热力图数据失败: {str(e)}")


@regional_analysis_router.post("/statistics")
async def get_regional_statistics(
    request: RegionalStatisticsRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取特定区域的详细统计"""
    try:
        filters = RegionalAnalysisFilters()
        filters.task_id = request.task_id
        filters.start_date = request.start_date
        filters.end_date = request.end_date

        analyzer = RegionalAnalyzer(db)
        stats = analyzer.get_regional_statistics(request.region, filters)

        return {
            "code": 200,
            "message": "获取区域统计成功",
            "data": stats,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取区域统计失败: {str(e)}")


@regional_analysis_router.get("/time-series")
async def get_regional_time_series(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    region: Optional[str] = Query(None, description="区域筛选"),
    granularity: Optional[str] = Query("day", description="时间粒度: day, week, month"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取区域时间序列数据"""
    try:
        filters = RegionalAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.region = region

        analyzer = RegionalAnalyzer(db)
        time_series = analyzer.get_time_series_data(filters, granularity)

        return {
            "code": 200,
            "message": "获取时间序列成功",
            "data": time_series,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取时间序列失败: {str(e)}")


@regional_analysis_router.get("/confidence-analysis")
async def get_confidence_analysis(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    region: Optional[str] = Query(None, description="区域筛选"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取置信度分析"""
    try:
        filters = RegionalAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.region = region

        analyzer = RegionalAnalyzer(db)
        query = analyzer.build_base_query(filters)
        confidence_analysis = analyzer.get_confidence_distribution(query, filters)

        return {
            "code": 200,
            "message": "获取置信度分析成功",
            "data": confidence_analysis,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取置信度分析失败: {str(e)}")


@regional_analysis_router.get("/summary")
async def get_regional_summary(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取区域分析摘要"""
    try:
        filters = RegionalAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date

        analyzer = RegionalAnalyzer(db)
        basic_stats = analyzer.get_basic_statistics(filters)

        # 获取简要的区域分布
        query = analyzer.build_base_query(filters)
        distribution = analyzer.get_regional_distribution(query, filters)

        # 获取坐标覆盖率
        coordinate_coverage = analyzer._calculate_coordinate_coverage(query)

        summary = {
            "basic_statistics": basic_stats,
            "top_regions": distribution.get("regions", [])[:5],
            "top_counts": distribution.get("counts", [])[:5],
            "coordinate_coverage": coordinate_coverage,
            "total_regions": distribution.get("total_regions", 0)
        }

        return {
            "code": 200,
            "message": "获取区域摘要成功",
            "data": summary,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取区域摘要失败: {str(e)}")


@regional_analysis_router.get("/export")
async def export_regional_data(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    region: Optional[str] = Query(None, description="区域筛选"),
    format: str = Query("json", description="导出格式: json, csv"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """导出区域分析数据"""
    try:
        filters = RegionalAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.region = region

        analyzer = RegionalAnalyzer(db)
        result = analyzer.analyze_data(filters)

        if not result.success:
            raise HTTPException(status_code=400, detail=result.message)

        if format == "json":
            return {
                "code": 200,
                "message": "数据导出成功",
                "data": result.data,
                "format": "json",
                "timestamp": datetime.now().isoformat()
            }
        elif format == "csv":
            # 这里可以实现CSV导出逻辑
            raise HTTPException(status_code=400, detail="CSV导出功能待实现")
        else:
            raise HTTPException(status_code=400, detail="不支持的导出格式")

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"导出数据失败: {str(e)}")